<!-- 岗位添加 -->
<template>
  <div>
    <el-card style="width: 98%; margin: 0 auto; margin-top: 10px">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入" style="width: 50%" />
        </el-form-item>
        <el-form-item label="权限配置" prop="menuIds">
          <el-tree
            ref="treeRef"
            :props="{ label: 'name' }"
            :data="list"
            node-key="id"
            show-checkbox
            :default-checked-keys="checkedKeys"
            @check-change="handleCheckChange"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 按钮 -->
    <div class="btn">
      <el-button>取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { getMenuList, RoleAdd, getRoleById } from "@/api/personel/position/position";
import { buildTree } from "@/utils/treeUtil";
import { MenuData, RoleAddParams, listData } from "@/api/personel/position/type";
import { useRouter, useRoute } from "vue-router";
let router = useRouter();
let route = useRoute();

let ruleForm = reactive<listData>({
  id: 0,
  name: "",
  menuIds: [],
});

// 根据id获取单条数据
const treeRef = ref<any>();
const checkedKeys = ref<number[]>([]);
const getRoleData = async () => {
  if (ruleForm.id) {
    let res = await getRoleById(ruleForm.id);
    checkedKeys.value = res.menuIds;
    Object.assign(ruleForm, res);
  }
};

// 获取权限列表
const list = ref<MenuData[]>();
const getList = async () => {
  let res: any = await getMenuList();
  list.value = buildTree(res.list);
};

// 获取选中的id
const handleCheckChange = (data: MenuData, checked: boolean, indeterminate: boolean) => {
  const addIds = (children: MenuData[]) => {
    children.forEach((child) => {
      if (!ruleForm.menuIds.includes(child.id)) {
        ruleForm.menuIds.push(child.id);
      }
      if (child.children) {
        addIds(child.children); // 递归处理子节点
      }
    });
  };

  if (checked) {
    // 添加当前节点和所有子节点的 ID
    if (!ruleForm.menuIds.includes(data.id)) {
      ruleForm.menuIds.push(data.id);
    }
    if (data.children) {
      addIds(data.children);
    }
  } else {
    // 移除当前节点和子节点的 ID
    ruleForm.menuIds = ruleForm.menuIds.filter((id) => id !== data.id);
    if (data.children) {
      data.children.forEach((child) => {
        ruleForm.menuIds = ruleForm.menuIds.filter((id) => id !== child.id);
        if (child.children) {
          child.children.forEach((grandChild) => {
            ruleForm.menuIds = ruleForm.menuIds.filter((id) => id !== grandChild.id);
          });
        }
      });
    }
  }
  // 确保 menuIds 只包含唯一值
  ruleForm.menuIds = [...new Set(ruleForm.menuIds)];
  console.log(ruleForm.menuIds);
  
};

// 提交
const submitForm = async () => {
  let rows = treeRef.value.getCheckedKeys();
  ruleForm.menuIds = rows;
  await RoleAdd(ruleForm);
  ElMessage.success("添加成功");
  ruleForm.name = "";
  ruleForm.menuIds = [];
  router.push("/personel/position");
};

const submit = () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  menuIds: [{ required: true, message: "请选择权限", trigger: "blur" }],
});

onMounted(() => {
  ruleForm.id = route.query?.id as unknown as number;
  getList();
  getRoleData();
});
</script>

<style scoped lang="less">
.btn {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>
